<template>
  <div class="user-center">
    <!-- 页面头部 -->
    <div class="page-header">
      <div
        class="header-bg"
        :style="{
          backgroundImage: `url(${userInfo.coverImage || '/images/default-cover.jpg'})`,
        }"
      ></div>
      <div class="container mx-auto px-4 py-8">
        <div class="header-content">
          <div class="user-profile">
            <div class="avatar-section">
              <div
                class="avatar-wrapper cursor-pointer"
                @click="showImageUploadDialog('avatar')"
              >
                <el-avatar
                  :size="120"
                  :src="userInfo.avatar"
                  class="user-avatar"
                >
                  <img src="/default-avatar.png" alt="默认头像" />
                </el-avatar>
                <div class="upload-mask">
                  <el-icon><Camera /></el-icon>
                  <span>更换头像</span>
                </div>
              </div>
            </div>
            <div class="user-info">
              <div class="flex items-center justify-between mb-4">
                <h1 class="user-name">{{ userInfo.nickname }}</h1>
                <div class="action-buttons flex flex-col items-end gap-2">
                  <div class="flex space-x-2">
                    <el-button @click="showVisitorsDialog = true">
                      <el-icon><View /></el-icon>
                      最近访客
                    </el-button>
                    <el-button @click="showSearchDialog = true">
                      <el-icon><Search /></el-icon>
                      搜索用户
                    </el-button>
                    <el-button @click="showQrcodeDialog = true">
                      <el-icon><Share /></el-icon>
                      分享名片
                    </el-button>
                  </div>
                  <el-button
                    type="primary"
                    @click="showImageUploadDialog('cover')"
                  >
                    <el-icon><Camera /></el-icon>
                    更换封面
                  </el-button>
                </div>
              </div>
              <p class="user-bio">
                {{ userInfo.bio || "这个人很懒，什么都没写~" }}
              </p>
              <div class="user-stats">
                <div
                  class="stat-item cursor-pointer"
                  @click="showMyPosts = true"
                >
                  <span class="number">{{ stats.postsCount }}</span>
                  <span class="label">动态</span>
                </div>
                <div
                  class="stat-item cursor-pointer"
                  @click="showFollowingDialog = true"
                >
                  <span class="number">{{ stats.followingCount }}</span>
                  <span class="label">关注</span>
                </div>
                <div
                  class="stat-item cursor-pointer"
                  @click="showFollowersDialog = true"
                >
                  <span class="number">{{ stats.followersCount }}</span>
                  <span class="label">粉丝</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="main-layout">
        <!-- 左侧导航 -->
        <div class="sidebar">
          <el-card class="menu-card">
            <template #header>
              <div class="card-header">
                <h2>个人中心</h2>
              </div>
            </template>
            <el-menu
              :default-active="activeMenu"
              class="user-menu"
              @select="handleMenuSelect"
            >
              <el-menu-item index="overview">
                <el-icon><House /></el-icon>
                <span>概览</span>
              </el-menu-item>

              <!-- 内容管理 -->
              <el-sub-menu index="content">
                <template #title>
                  <el-icon><Document /></el-icon>
                  <span>内容管理</span>
                </template>
                <el-menu-item index="topics">
                  <el-icon><ChatDotRound /></el-icon>
                  <span>参与的话题</span>
                </el-menu-item>
                <el-menu-item index="activities">
                  <el-icon><Calendar /></el-icon>
                  <span>参与的活动</span>
                </el-menu-item>
                <el-menu-item index="articles">
                  <el-icon><Document /></el-icon>
                  <span>发表的文章</span>
                </el-menu-item>
                <el-menu-item index="guides">
                  <el-icon><Location /></el-icon>
                  <span>发表的攻略</span>
                </el-menu-item>
                <el-menu-item index="photos">
                  <el-icon><Picture /></el-icon>
                  <span>发布的摄影</span>
                </el-menu-item>
              </el-sub-menu>

              <!-- 订单中心 -->
              <el-sub-menu index="order">
                <template #title>
                  <el-icon><Tickets /></el-icon>
                  <span>订单中心</span>
                </template>
                <el-menu-item index="orders">
                  <el-icon><List /></el-icon>
                  <span>我的订单</span>
                </el-menu-item>
                <el-menu-item index="cart">
                  <el-icon><ShoppingCart /></el-icon>
                  <span>购物车</span>
                </el-menu-item>
                <el-menu-item index="address">
                  <el-icon><Location /></el-icon>
                  <span>收货地址</span>
                </el-menu-item>
              </el-sub-menu>

              <!-- 互动中心 -->
              <el-sub-menu index="interaction">
                <template #title>
                  <el-icon><ChatDotRound /></el-icon>
                  <span>互动中心</span>
                </template>
                <el-menu-item index="favorites">
                  <el-icon><Star /></el-icon>
                  <span>我的收藏</span>
                </el-menu-item>
                <el-menu-item index="reviews">
                  <el-icon><ChatDotRound /></el-icon>
                  <span>我的评价</span>
                </el-menu-item>
                <el-menu-item index="messages" class="messages-menu-item">
                  <el-icon><Message /></el-icon>
                  <span>消息中心</span>
                  <div class="badge-wrapper">
                    <el-badge
                      v-if="unreadCount"
                      :value="unreadCount"
                      class="custom-badge"
                    />
                  </div>
                </el-menu-item>
              </el-sub-menu>

              <!-- 账号设置 -->
              <el-sub-menu index="account">
                <template #title>
                  <el-icon><Setting /></el-icon>
                  <span>账号设置</span>
                </template>
                <el-menu-item index="settings">
                  <el-icon><Setting /></el-icon>
                  <span>基本设置</span>
                </el-menu-item>
                <el-menu-item index="preview" @click="handlePreview">
                  <el-icon><View /></el-icon>
                  <span>预览主页</span>
                </el-menu-item>
              </el-sub-menu>
            </el-menu>
          </el-card>
        </div>

        <!-- 中间内容区 -->
        <div class="main-content" :class="{ 'with-sidebar': isOverviewPage }">
          <router-view />
        </div>

        <!-- 右侧边栏 -->
        <div v-if="isOverviewPage" class="right-sidebar">
          <!-- 待处理事项 -->
          <el-card class="todo-card">
            <!-- 待处理事项内容 -->
          </el-card>
        </div>
      </div>
    </div>

    <!-- 我的动态弹窗 -->
    <el-dialog
      v-model="showMyPosts"
      title="我的动态"
      width="1000px"
      :close-on-click-modal="false"
      destroy-on-close
      class="my-posts-dialog"
    >
      <MyPosts />
    </el-dialog>

    <!-- 我的关注弹窗 -->
    <el-dialog
      v-model="showFollowingDialog"
      :title="`我的关注 (${followingList.length})`"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
      class="following-dialog"
    >
      <div class="following-list h-[60vh] overflow-y-auto pr-2">
        <div
          v-for="user in followingList"
          :key="user.id"
          class="user-item flex items-center justify-between p-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg"
        >
          <div class="flex items-center">
            <el-avatar :size="40" :src="user.avatar" />
            <div class="ml-3">
              <div class="font-medium text-gray-900 dark:text-white">
                {{ user.nickname }}
              </div>
              <div class="text-sm text-gray-500 dark:text-gray-400">
                {{ user.signature }}
              </div>
            </div>
          </div>
          <el-button size="small" type="primary" @click="handleUnfollow(user)"
            >取消关注</el-button
          >
        </div>
        <el-empty v-if="!followingList.length" description="暂无关注" />
      </div>
    </el-dialog>

    <!-- 我的粉丝弹窗 -->
    <el-dialog
      v-model="showFollowersDialog"
      :title="`我的粉丝 (${followersList.length})`"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
      class="followers-dialog"
    >
      <div class="followers-list h-[60vh] overflow-y-auto pr-2">
        <div
          v-for="user in followersList"
          :key="user.id"
          class="user-item flex items-center justify-between p-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg"
        >
          <div class="flex items-center">
            <el-avatar :size="40" :src="user.avatar" />
            <div class="ml-3">
              <div class="font-medium text-gray-900 dark:text-white">
                {{ user.nickname }}
              </div>
              <div class="text-sm text-gray-500 dark:text-gray-400">
                {{ user.signature }}
              </div>
            </div>
          </div>
          <el-button
            size="small"
            :type="user.isFollowing ? 'default' : 'primary'"
            @click="handleFollowFan(user)"
          >
            {{ user.isFollowing ? "已关注" : "关注" }}
          </el-button>
        </div>
        <el-empty v-if="!followersList.length" description="暂无粉丝" />
      </div>
    </el-dialog>

    <!-- 最近访客弹窗 -->
    <el-dialog
      v-model="showVisitorsDialog"
      :title="`最近访客 (${visitorsList.length})`"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
      class="visitors-dialog"
    >
      <div class="visitors-list h-[60vh] overflow-y-auto pr-2">
        <div
          v-for="visitor in visitorsList"
          :key="visitor.id"
          class="user-item flex items-center justify-between p-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg"
        >
          <div class="flex items-center">
            <el-avatar :size="40" :src="visitor.avatar" />
            <div class="ml-3">
              <div class="font-medium text-gray-900 dark:text-white">
                {{ visitor.nickname }}
              </div>
              <div class="text-sm text-gray-500 dark:text-gray-400">
                {{ visitor.visitTime }}
              </div>
            </div>
          </div>
          <el-button
            size="small"
            :type="visitor.isFollowing ? 'default' : 'primary'"
            @click="handleFollowVisitor(visitor)"
          >
            {{ visitor.isFollowing ? "已关注" : "关注" }}
          </el-button>
        </div>
        <el-empty v-if="!visitorsList.length" description="暂无访客记录" />
      </div>
    </el-dialog>

    <!-- 搜索用户弹窗 -->
    <el-dialog
      v-model="showSearchDialog"
      title="搜索用户"
      width="600px"
      :close-on-click-modal="false"
      destroy-on-close
      class="search-dialog"
    >
      <div class="search-box mb-6">
        <el-input
          v-model="searchQuery"
          placeholder="输入用户名、手机号、邮箱或粘贴名片链接搜索"
          class="mb-4"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="search-results h-[50vh] overflow-y-auto pr-2">
        <div
          v-for="user in searchResults"
          :key="user.id"
          class="user-item flex items-center justify-between p-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 rounded-lg"
        >
          <div class="flex items-center">
            <el-avatar :size="40" :src="user.avatar" />
            <div class="ml-3">
              <div class="font-medium text-gray-900 dark:text-white">
                {{ user.nickname }}
              </div>
              <div class="text-sm text-gray-500 dark:text-gray-400">
                {{ user.signature }}
              </div>
            </div>
          </div>
          <el-button
            size="small"
            :type="user.isFollowing ? 'default' : 'primary'"
            @click="handleFollowUser(user)"
          >
            {{ user.isFollowing ? "已关注" : "关注" }}
          </el-button>
        </div>
        <el-empty
          v-if="!searchResults.length"
          :description="searchQuery ? '未找到相关用户' : '输入关键词搜索用户'"
        />
      </div>
    </el-dialog>

    <!-- 分享名片弹窗 -->
    <el-dialog
      v-model="showQrcodeDialog"
      title="分享我的名片"
      width="400px"
      :close-on-click-modal="false"
      destroy-on-close
      class="share-dialog"
    >
      <div class="share-content flex flex-col items-center">
        <el-avatar :size="80" :src="userInfo.avatar" class="mb-4" />
        <h3 class="text-lg font-medium mb-2">{{ userInfo.nickname }}</h3>
        <p class="text-gray-500 mb-6">{{ userInfo.bio }}</p>

        <!-- 个人主页链接 -->
        <div class="share-link w-full mb-6">
          <div
            class="flex items-center gap-2 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg"
          >
            <input
              ref="linkInput"
              type="text"
              :value="profileUrl"
              class="flex-1 bg-transparent border-none outline-none text-sm"
              readonly
            />
            <el-button type="primary" link @click="copyLink">
              复制链接
            </el-button>
          </div>
        </div>

        <!-- 社交平台分享 -->
        <div class="share-platforms">
          <div class="text-sm text-gray-500 mb-4 text-center">
            分享到社交平台
          </div>
          <div class="flex items-center justify-center gap-6">
            <!-- 微信分享 -->
            <div class="share-item cursor-pointer" @click="shareToWeChat">
              <el-image
                src="https://mp.weixin.qq.com/favicon.ico"
                class="w-10 h-10 rounded-lg"
              />
              <span class="text-xs mt-1">微信</span>
            </div>

            <!-- QQ分享 -->
            <div class="share-item cursor-pointer" @click="shareToQQ">
              <el-image
                src="https://qzone.qq.com/favicon.ico"
                class="w-10 h-10 rounded-lg"
              />
              <span class="text-xs mt-1">QQ</span>
            </div>

            <!-- 微博分享 -->
            <div class="share-item cursor-pointer" @click="shareToWeibo">
              <el-image
                src="https://weibo.com/favicon.ico"
                class="w-10 h-10 rounded-lg"
              />
              <span class="text-xs mt-1">微博</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 图片上传模态框 -->
    <ImageEditor
      v-model="showImageUpload"
      :title="uploadType === 'avatar' ? '更换头像' : '更换封面'"
      :upload-action="
        uploadType === 'avatar' ? '/api/upload/avatar' : '/api/upload/cover'
      "
      :aspect-ratio="uploadType === 'avatar' ? 1 : 3"
      :history-images="historyImages"
      @success="handleImageSuccess"
      @select="handleHistorySelect"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/stores/user";
import { useThemeStore } from "@/stores/theme";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUserProfile, updateUserProfile } from "@/api/user";
import {
  Camera,
  Tickets,
  Star,
  ChatDotRound,
  Message,
  House,
  Setting,
  Wallet,
  Box,
  View,
  Search,
  Share,
  Link,
  Upload,
  Picture,
  Crop,
  Refresh,
  Document,
  Calendar,
  Location,
  ShoppingCart,
  List,
} from "@element-plus/icons-vue";
import MyPosts from "@/components/community/MyPosts.vue";
import ImageEditor from "@/components/common/ImageEditor.vue";
import "vue-cropper/dist/index.css";
import { VueCropper } from "vue-cropper";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const themeStore = useThemeStore();

// 主题状态
const isDarkMode = computed(() => themeStore.isDark);

// 更新主题相关的DOM元素
const updateThemeElements = (isDark) => {
  // 更新自定义组件的主题
  const userCenter = document.querySelector(".user-center");
  if (userCenter) {
    userCenter.classList.toggle("dark", isDark);
  }

  // 更新菜单主题
  const menuCard = document.querySelector(".menu-card");
  if (menuCard) {
    menuCard.classList.toggle("dark", isDark);
  }

  // 更新对话框主题
  document.querySelectorAll(".el-dialog").forEach((dialog) => {
    dialog.classList.toggle("dark", isDark);
  });

  // 更新卡片主题
  document.querySelectorAll(".el-card").forEach((card) => {
    card.classList.toggle("dark", isDark);
  });

  // 更新表单项主题
  document.querySelectorAll(".el-form-item").forEach((item) => {
    item.classList.toggle("dark", isDark);
  });

  // 更新输入框主题
  document
    .querySelectorAll(".el-input__wrapper, .el-textarea__wrapper")
    .forEach((input) => {
      input.classList.toggle("dark", isDark);
    });

  // 更新按钮主题
  document.querySelectorAll(".el-button").forEach((button) => {
    button.classList.toggle("dark", isDark);
  });
};

// 监听主题变化并同步样式
watch(isDarkMode, updateThemeElements);

// 当前激活的菜单
const activeMenu = ref(route.path.split("/")[2] || "overview");

// 判断是否是概览页面
const isOverviewPage = computed(() => {
  return route.name === "UserOverview";
});

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    const menuIndex = newPath.split("/")[2] || "overview";
    activeMenu.value = menuIndex;
  },
);

// 未读消息数量
const unreadCount = ref(5);

// 用户信息
const userInfo = ref({
  username: "",
  nickname: "",
  avatar: "/images/avatars/default.jpg",
  bio: "",
  phone: "",
  email: "",
  createTime: "",
  coverImage: "/images/default-cover.jpg",
});

// 用户统计
const stats = ref({
  postsCount: 15,
  followingCount: 56,
  followersCount: 34,
});

// 待处理事项统计
const pendingStats = ref({
  unpaidCount: 2,
  unusedCount: 3,
  unreviewedCount: 5,
});

// 最近浏览记录
const recentViews = ref([
  {
    id: 1,
    type: "spot",
    title: "贵港江滨公园",
    image: "/images/spots/spot1.jpg",
    viewTime: "2024-03-19 15:30:00",
  },
  {
    id: 2,
    type: "product",
    title: "贵港特色手工艺品",
    image: "/images/products/product1.jpg",
    viewTime: "2024-03-18 14:20:00",
  },
]);

// 显示我的动态弹窗
const showMyPosts = ref(false);

// 显示我的关注弹窗
const showFollowingDialog = ref(false);

// 显示我的粉丝弹窗
const showFollowersDialog = ref(false);

// 关注列表
const followingList = ref([
  {
    id: 1,
    nickname: "用户1",
    avatar: "/images/avatars/user1.jpg",
    signature: "热爱旅行的探索者",
  },
  {
    id: 2,
    nickname: "用户2",
    avatar: "/images/avatars/user2.jpg",
    signature: "热爱旅行的探索者",
  },
]);

// 粉丝列表
const followersList = ref([
  {
    id: 1,
    nickname: "用户1",
    avatar: "/images/avatars/user1.jpg",
    signature: "热爱旅行的探索者",
    isFollowing: true,
  },
  {
    id: 2,
    nickname: "用户2",
    avatar: "/images/avatars/user2.jpg",
    signature: "热爱旅行的探索者",
    isFollowing: false,
  },
]);

// 最近访客列表
const visitorsList = ref([
  {
    id: 1,
    nickname: "用户1",
    avatar: "/images/avatars/user1.jpg",
    visitTime: "2024-03-19 15:30:00",
    isFollowing: true,
  },
  {
    id: 2,
    nickname: "用户2",
    avatar: "/images/avatars/user2.jpg",
    visitTime: "2024-03-18 14:20:00",
    isFollowing: false,
  },
]);

// 搜索查询
const searchQuery = ref("");

// 搜索结果
const searchResults = ref([]);

// 显示最近访客弹窗
const showVisitorsDialog = ref(false);

// 显示搜索用户弹窗
const showSearchDialog = ref(false);

// 显示分享名片弹窗
const showQrcodeDialog = ref(false);

// 二维码URL
const qrcodeUrl = ref("");

// 个人主页 URL
const profileUrl = computed(() => {
  const baseUrl = window.location.origin;
  return `${baseUrl}/user/profile/${userInfo.value.username}`;
});

// 复制链接
const copyLink = async () => {
  try {
    await navigator.clipboard.writeText(profileUrl.value);
    ElMessage.success("链接已复制到剪贴板");
  } catch (err) {
    ElMessage.error("复制失败，请手动复制");
  }
};

// 分享到微信
const shareToWeChat = () => {
  // 使用微信 SDK 分享
  if (typeof wx !== "undefined") {
    wx.ready(() => {
      wx.shareAppMessage({
        title: `${userInfo.value.nickname}的个人主页`,
        desc: userInfo.value.bio,
        link: profileUrl.value,
        imgUrl: userInfo.value.avatar,
        success: () => {
          ElMessage.success("分享成功");
          showQrcodeDialog.value = false;
        },
        cancel: () => {
          ElMessage.info("取消分享");
        },
      });
    });
  } else {
    // 如果在非微信环境，则显示提示
    ElMessageBox.alert("请在微信中打开进行分享", "提示", {
      confirmButtonText: "确定",
    });
  }
};

// 分享到 QQ
const shareToQQ = () => {
  const params = {
    url: profileUrl.value,
    title: `${userInfo.value.nickname}的个人主页`,
    desc: userInfo.value.bio,
    pics: userInfo.value.avatar,
  };

  const queryString = Object.entries(params)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join("&");

  window.open(
    `https://connect.qq.com/widget/shareqq/index.html?${queryString}`,
    "_blank",
  );
  showQrcodeDialog.value = false;
};

// 分享到微博
const shareToWeibo = () => {
  const params = {
    url: profileUrl.value,
    title: `${userInfo.value.nickname}的个人主页 - ${userInfo.value.bio}`,
    pic: userInfo.value.avatar,
  };

  const queryString = Object.entries(params)
    .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
    .join("&");

  window.open(
    `https://service.weibo.com/share/share.php?${queryString}`,
    "_blank",
  );
  showQrcodeDialog.value = false;
};

// 处理菜单选择
const handleMenuSelect = (index) => {
  activeMenu.value = index;
  router.push(`/user/${index}`);
};

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 头像上传成功
const handleAvatarSuccess = (response) => {
  userInfo.value.avatar = response.url;
  ElMessage.success("头像更新成功");
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

// 手机号码脱敏
const maskPhone = (phone) => {
  return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2") : "";
};

// 邮箱脱敏
const maskEmail = (email) => {
  if (!email) return "";
  const [username, domain] = email.split("@");
  const maskedUsername =
    username.charAt(0) + "****" + username.charAt(username.length - 1);
  return `${maskedUsername}@${domain}`;
};

// 获取用户信息
const getUserInfo = async () => {
  try {
    // 调用获取用户信息API
    const response = await getUserProfile();
    console.log("获取到的原始响应:", response);
    
    // 正确提取响应中的data属性
    const userProfile = response && response.data ? response.data : response;
    console.log("提取的用户数据:", userProfile);
    
    if (userProfile) {
      // 更新用户信息
      userInfo.value = {
        ...userInfo.value,
        username: userProfile.username || "",
        nickname: userProfile.nickname || "用户",
        avatar: userProfile.avatar || "/images/avatars/default.jpg",
        bio: userProfile.bio || "这个人很懒，什么都没写~",
        phone: userProfile.phone || "",
        email: userProfile.email || "",
        createTime: userProfile.createTime || "",
        coverImage: userProfile.coverImage || "/images/default-cover.jpg"
      };
    }
  } catch (error) {
    console.error("获取用户信息失败:", error);
    ElMessage.error("获取用户信息失败");
  }
};

// 获取浏览类型文本
const getViewTypeText = (type) => {
  const typeMap = {
    spot: "景点",
    product: "商品",
    hotel: "酒店",
  };
  return typeMap[type] || "未知";
};

// 清空浏览历史
const clearHistory = async () => {
  try {
    await ElMessageBox.confirm("确定要清空浏览历史吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // TODO: 调用清空历史API
    recentViews.value = [];
    ElMessage.success("浏览历史已清空");
  } catch (error) {
    if (error === "cancel") return;
    ElMessage.error("清空历史失败");
  }
};

// 查看详情
const viewDetail = (item) => {
  const routeMap = {
    spot: `/spots/${item.id}`,
    product: `/shop/product/${item.id}`,
    hotel: `/hotel/${item.id}`,
  };
  router.push(routeMap[item.type]);
};

// 取消关注
const handleUnfollow = async (user) => {
  try {
    await ElMessageBox.confirm("确定要取消关注该用户吗？", "取消关注", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    // TODO: 调用取消关注API
    const index = followingList.value.findIndex((item) => item.id === user.id);
    if (index !== -1) {
      followingList.value.splice(index, 1);
      stats.value.followingCount--;
    }
    ElMessage.success("已取消关注");
  } catch {
    // 用户取消操作
  }
};

// 关注/取消关注粉丝
const handleFollowFan = async (user) => {
  try {
    // TODO: 调用关注/取消关注API
    user.isFollowing = !user.isFollowing;
    if (user.isFollowing) {
      stats.value.followingCount++;
      ElMessage.success("关注成功");
    } else {
      stats.value.followingCount--;
      ElMessage.success("已取消关注");
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 处理最近访客
const handleFollowVisitor = async (visitor) => {
  try {
    // TODO: 调用处理最近访客API
    visitor.isFollowing = !visitor.isFollowing;
    if (visitor.isFollowing) {
      stats.value.followingCount++;
      ElMessage.success("关注成功");
    } else {
      stats.value.followingCount--;
      ElMessage.success("已取消关注");
    }
  } catch (error) {
    console.error("处理最近访客失败:", error);
    ElMessage.error("处理最近访客失败");
  }
};

// 处理搜索用户
const handleSearch = async () => {
  try {
    // TODO: 调用搜索用户API
    // const { data } = await api.searchUser(searchQuery.value);
    // searchResults.value = data;
  } catch (error) {
    console.error("搜索用户失败:", error);
    ElMessage.error("搜索用户失败");
  }
};

// 处理关注用户
const handleFollowUser = async (user) => {
  try {
    // TODO: 调用关注用户API
    user.isFollowing = true;
    stats.value.followingCount++;
    ElMessage.success("关注成功");
  } catch (error) {
    console.error("关注用户失败:", error);
    ElMessage.error("关注用户失败");
  }
};

// 搜索相关
const isSearching = ref(false);
const searchUserDialogVisible = ref(false);

// 社交平台配置
const socialPlatforms = [
  {
    name: "微信",
    type: "wechat",
    icon: "https://mp.weixin.qq.com/favicon.ico",
  },
  {
    name: "QQ",
    type: "qq",
    icon: "https://qzone.qq.com/favicon.ico",
  },
  {
    name: "微博",
    type: "weibo",
    icon: "https://weibo.com/favicon.ico",
  },
];

// 处理搜索输入
const handleSearchInput = async (value) => {
  if (!value) {
    searchResults.value = [];
    return;
  }

  // 如果是链接格式，不执行搜索
  if (value.includes("/user/profile/")) return;

  isSearching.value = true;
  try {
    // TODO: 调用搜索API
    // const { data } = await api.searchUsers(value);
    // searchResults.value = data;

    // 模拟数据
    searchResults.value = [
      {
        id: 1,
        nickname: "测试用户",
        avatar: "/default-avatar.png",
        bio: "这是一个测试用户",
      },
    ];
  } catch (error) {
    console.error("搜索失败:", error);
    ElMessage.error("搜索失败");
  } finally {
    isSearching.value = false;
  }
};

// 处理粘贴上传
const handlePaste = async (event) => {
  const items = (event.clipboardData || event.originalEvent.clipboardData)
    .items;
  for (const item of items) {
    if (item.type.indexOf("image") === 0) {
      const file = item.getAsFile();
      beforeImageUpload(file);
      break;
    }
  }
};

// 查看用户主页
const viewUserProfile = (user) => {
  router.push(`/user/profile/${user.username}`);
  searchUserDialogVisible.value = false;
};

// 分享到社交平台
const shareToSocial = (platform) => {
  const shareData = {
    title: `${userInfo.value.nickname}的个人主页`,
    desc: userInfo.value.bio,
    link: profileUrl.value,
    image: userInfo.value.avatar,
  };

  switch (platform) {
    case "wechat":
      shareToWeChat(shareData);
      break;
    case "qq":
      shareToQQ(shareData);
      break;
    case "weibo":
      shareToWeibo(shareData);
      break;
  }
};

// 图片上传相关
const showImageUpload = ref(false);
const uploadType = ref("avatar"); // 'avatar' | 'cover'
const historyImages = ref([
  // 模拟数据，实际应从API获取
  {
    url: "/images/history-1.jpg",
    createTime: "2024-03-19 15:30:00",
  },
  {
    url: "/images/history-2.jpg",
    createTime: "2024-03-18 14:20:00",
  },
]);

// 显示图片上传对话框
const showImageUploadDialog = (type) => {
  uploadType.value = type;
  showImageUpload.value = true;
};

// 处理图片上传成功
const handleImageSuccess = async ({ url }) => {
  if (uploadType.value === "avatar") {
    userInfo.value.avatar = url;
    // 更新头像到服务器
    await updateUserAvatar(url);
    // 同步更新全局头像
    updateGlobalAvatar(url);
  } else {
    userInfo.value.coverImage = url;
    // 更新封面图到服务器
    await updateUserCover(url);
    // 更新背景图片样式
    const headerBg = document.querySelector(".header-bg");
    if (headerBg) {
      headerBg.style.backgroundImage = `url(${url})`;
    }
  }
  ElMessage.success(
    `${uploadType.value === "avatar" ? "头像" : "封面"}更新成功`,
  );
};

// 处理历史图片选择
const handleHistorySelect = async (image) => {
  if (uploadType.value === "avatar") {
    userInfo.value.avatar = image.url;
    // 更新头像到服务器
    await updateUserAvatar(image.url);
    // 同步更新全局头像
    updateGlobalAvatar(image.url);
  } else {
    userInfo.value.coverImage = image.url;
    // 更新封面图到服务器
    await updateUserCover(image.url);
    // 更新背景图片样式
    const headerBg = document.querySelector(".header-bg");
    if (headerBg) {
      headerBg.style.backgroundImage = `url(${image.url})`;
    }
  }
  ElMessage.success(`${uploadType.value === "avatar" ? "头像" : "封面"}已更新`);
};

// 更新全局导航栏头像
const updateGlobalAvatar = (avatarUrl) => {
  try {
    // 更新userStore中的头像信息
    if (userStore.userInfo) {
      // 使用setUserInfo方法更新用户信息
      userStore.setUserInfo({
        ...userStore.userInfo,
        avatar: avatarUrl
      });
      console.log("全局头像已更新");
    }
  } catch (error) {
    console.error("更新全局头像失败:", error);
  }
};

// 更新用户头像到服务器
const updateUserAvatar = async (avatarUrl) => {
  try {
    await updateUserProfile({
      avatar: avatarUrl
    });
    console.log("头像已同步到服务器");
  } catch (error) {
    console.error("更新头像失败:", error);
    ElMessage.error("头像保存失败，请重试");
  }
};

// 更新用户封面图到服务器
const updateUserCover = async (coverUrl) => {
  try {
    await updateUserProfile({
      coverImage: coverUrl
    });
    console.log("封面图已同步到服务器");
  } catch (error) {
    console.error("更新封面图失败:", error);
    ElMessage.error("封面图保存失败，请重试");
  }
};

// 处理预览个人主页
const handlePreview = () => {
  router.push(`/user/profile/${userInfo.value.id}`);
};

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// ResizeObserver实例
let resizeObserver = null;

// 在组件挂载时初始化主题
onMounted(() => {
  getUserInfo();

  // 初始化主题相关元素
  updateThemeElements(isDarkMode.value);

  // 监听主题变化事件
  const handleThemeChange = (event) => {
    updateThemeElements(event.detail.isDark);
  };

  document.addEventListener("theme-changed", handleThemeChange);

  // 保存事件处理函数的引用，以便在组件卸载时移除
  themeChangeHandler.value = handleThemeChange;

  // 初始化ResizeObserver
  const mainContent = document.querySelector(".main-content");
  if (mainContent) {
    resizeObserver = new ResizeObserver(
      debounce((entries) => {
        for (const entry of entries) {
          if (entry.target === mainContent) {
            entry.target.style.minHeight = `${entry.contentRect.height}px`;
          }
        }
      }, 16),
    );
    resizeObserver.observe(mainContent);
  }
});

// 保存事件处理函数的引用
const themeChangeHandler = ref(null);

onUnmounted(() => {
  // 清理ResizeObserver
  if (resizeObserver) {
    resizeObserver.disconnect();
    resizeObserver = null;
  }

  // 移除主题变化事件监听
  if (themeChangeHandler.value) {
    document.removeEventListener("theme-changed", themeChangeHandler.value);
  }
});
</script>

<style lang="scss" scoped>
.user-center {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors duration-300;

  .page-header {
    @apply relative bg-white dark:bg-gray-800 shadow-sm transition-colors duration-300 overflow-hidden;

    .header-bg {
      @apply absolute inset-0 bg-center bg-cover bg-no-repeat;
      &::after {
        content: "";
        @apply absolute inset-0 bg-black/30;
      }
    }

    .container {
      @apply relative z-10;
    }

    .header-content {
      @apply relative;

      .user-profile {
        @apply flex items-center gap-8;

        .avatar-section {
          @apply relative flex-shrink-0;

          .avatar-wrapper {
            @apply relative cursor-pointer;

            .user-avatar {
              @apply ring-4 ring-white dark:ring-gray-800 ring-offset-2 ring-offset-white dark:ring-offset-gray-800 transition-all duration-300;
            }

            .upload-mask {
              @apply absolute inset-0 flex flex-col items-center justify-center bg-black/50 rounded-full opacity-0 transition-opacity duration-300;

              .el-icon {
                @apply text-2xl text-white mb-1;
              }

              span {
                @apply text-sm text-white;
              }
            }

            &:hover {
              .user-avatar {
                @apply ring-primary-500 dark:ring-primary-400;
              }

              .upload-mask {
                @apply opacity-100;
              }
            }
          }
        }

        .user-info {
          @apply flex-1;

          .user-name {
            @apply text-2xl font-bold text-white mb-2;
          }

          .user-bio {
            @apply text-gray-200 mb-4;
          }

          .user-stats {
            @apply flex items-center gap-8;

            .stat-item {
              @apply flex flex-col items-center;

              .number {
                @apply text-xl font-bold text-white;
              }

              .label {
                @apply text-sm text-gray-200 mt-1;
              }
            }
          }
        }
      }
    }
  }

  .main-layout {
    @apply grid gap-6;
    grid-template-columns: 260px minmax(0, 1fr);

    .sidebar {
      @apply w-64 flex-shrink-0;
      position: sticky;
      top: 24px;
      height: fit-content;
      contain: content;
    }

    .main-content {
      @apply flex-1 min-w-0;
      contain: content;

      &.with-sidebar {
        grid-template-columns: minmax(0, 1fr) 260px;
      }
    }

    .right-sidebar {
      @apply w-64 flex-shrink-0;
      position: sticky;
      top: 24px;
      height: fit-content;
      contain: content;

      .todo-card {
        @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden;
      }
    }
  }

  .pending-section {
    .pending-list {
      @apply grid grid-cols-4 gap-4;

      .pending-item {
        @apply flex items-center p-4 bg-gray-50 dark:bg-gray-800 rounded-lg cursor-pointer transition-all duration-300;

        &:hover {
          @apply transform scale-105 shadow-md;
        }

        .item-icon {
          @apply w-12 h-12 rounded-full flex items-center justify-center mr-4 flex-shrink-0;

          &.warning {
            @apply bg-yellow-50 dark:bg-yellow-900/50 text-yellow-600 dark:text-yellow-400;
          }

          &.primary {
            @apply bg-primary-50 dark:bg-primary-900/50 text-primary-600 dark:text-primary-400;
          }

          &.success {
            @apply bg-green-50 dark:bg-green-900/50 text-green-600 dark:text-green-400;
          }

          &.danger {
            @apply bg-red-50 dark:bg-red-900/50 text-red-600 dark:text-red-400;
          }

          .el-icon {
            @apply text-2xl;
          }
        }

        .item-info {
          @apply flex-1 min-w-0;

          .item-title {
            @apply text-sm text-gray-600 dark:text-gray-400 whitespace-nowrap;
          }

          .item-count {
            @apply text-xl font-bold text-gray-900 dark:text-white mt-1;
          }
        }
      }
    }
  }

  .recent-section {
    .recent-list {
      @apply grid grid-cols-2 gap-4;

      .recent-item {
        @apply flex items-center p-3 bg-gray-50 dark:bg-gray-800 rounded-lg cursor-pointer transition-all duration-300;

        &:hover {
          @apply bg-gray-100 dark:bg-gray-700;

          .item-image {
            @apply transform scale-105;
          }
        }

        .item-image {
          @apply w-20 h-20 rounded-lg object-cover transition-transform duration-300;
        }

        .item-info {
          @apply flex-1 ml-4;

          .item-title {
            @apply text-sm font-medium text-gray-900 dark:text-white line-clamp-1;
          }

          .item-type {
            @apply text-xs text-primary-600 dark:text-primary-400 mt-1;
          }

          .item-time {
            @apply text-xs text-gray-500 dark:text-gray-400 mt-1;
          }
        }
      }
    }
  }
}

// 恢复个人资料卡片样式
.profile-card {
  @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden;

  :deep(.el-card__header) {
    @apply p-0 border-b-0;

    .card-header {
      @apply px-6 py-4 flex items-center justify-between border-b border-gray-100 dark:border-gray-700;

      h2 {
        @apply text-lg font-medium text-gray-900 dark:text-white;
      }
    }
  }

  .profile-info {
    @apply p-6 space-y-4;

    .info-item {
      @apply flex items-center p-4 bg-gray-50 dark:bg-gray-800 rounded-lg transition-all duration-300 hover:shadow-md;

      .label {
        @apply text-gray-500 dark:text-gray-400 w-24;
      }

      .value {
        @apply text-gray-900 dark:text-gray-100 flex-1;
      }
    }
  }
}

// 修改右侧数据卡片布局
.right-sidebar {
  @apply w-64 flex-shrink-0;

  .todo-card {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden;
  }
}

.share-dialog {
  .share-content {
    @apply text-center;
  }

  .share-link {
    input {
      @apply text-gray-600 dark:text-gray-300;

      &::selection {
        @apply bg-primary-100 dark:bg-primary-900;
      }
    }
  }

  .share-platforms {
    @apply w-full;

    .share-item {
      @apply flex flex-col items-center transition-transform duration-300;

      &:hover {
        @apply transform scale-110;
      }

      span {
        @apply text-gray-600 dark:text-gray-400;
      }
    }
  }
}

.cover-image {
  @apply relative transition-all duration-300;

  &:hover {
    .cover-actions {
      @apply opacity-100;
    }
  }

  .cover-actions {
    @apply opacity-0 transition-opacity duration-300;
  }
}

.menu-card {
  @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden;

  :deep(.el-card__body) {
    @apply p-0;
  }

  :deep(.el-menu) {
    @apply border-none bg-white dark:bg-gray-800;

    .el-menu-item,
    .el-sub-menu__title {
      @apply text-base text-gray-900 dark:text-gray-100;
      font-size: 16px;

      .el-icon {
        font-size: 18px;
        @apply text-gray-600 dark:text-gray-400;
      }

      &:hover {
        @apply bg-gray-100 dark:bg-gray-700;
      }

      &.is-active {
        @apply text-primary-600 dark:text-primary-400 bg-primary-50 dark:bg-primary-900/20;
      }
    }

    .el-menu-item-group__title {
      @apply text-sm text-gray-500 dark:text-gray-400;
    }

    .el-sub-menu {
      .el-menu-item {
        @apply text-sm text-gray-800 dark:text-gray-200;
        font-size: 14px;

        .el-icon {
          font-size: 16px;
          @apply text-gray-600 dark:text-gray-400;
        }

        &:hover {
          @apply bg-gray-100 dark:bg-gray-700;
        }

        &.is-active {
          @apply text-primary-600 dark:text-primary-400 bg-primary-50 dark:bg-primary-900/20;
        }
      }
    }
  }

  :deep(.el-card__header) {
    @apply p-0 border-b border-gray-100 dark:border-gray-700;

    .card-header {
      @apply px-6 py-4;

      h2 {
        @apply text-lg font-medium text-gray-900 dark:text-white;
      }
    }
  }
}
</style>
